﻿using CarEdge.Infrastructure.Attr;
using CarEdge.Infrastructure.Dto.Request.Consume;
using CarEdge.Infrastructure.Dto.Request.Reservation;
using CarEdge.Infrastructure.Dto.Response.Org;
using CarEdge.Infrastructure.Dto.Response.Product;
using CarEdge.Infrastructure.Dto.Response.Reservation;
using CarEdge.Infrastructure.Dto.Response;
using CarEdge.Infrastructure.EFCore.MySql;
using CarEdge.Infrastructure.IOC.Reservation;
using CarEdge.Service.Interface.Reservation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Crm.Infrastructure.Tools;
using Microsoft.EntityFrameworkCore;

namespace CarEdge.Service.Instance.Reservation
{
    [Inject_]
    public class Reservation_Service : Base_Service, I_Reservation_EFCore
    {
        public readonly Reservation_IOC _reservation_IOC;
        public Reservation_Service(Reservation_IOC reservation_IOC)
        {
            _reservation_IOC = reservation_IOC;

        }

        public async Task<Api_Response_Dto> Recharge(Consume_Request_Dto dto)
        {
            var cid = _reservation_IOC._customer_EFCore.QueryAll(d => d.CPhone == dto.phone).SingleOrDefault()!.CId;
            var vid = _reservation_IOC._vIP_EFCore.QueryAll(d => d.VCid == cid).SingleOrDefault()!.VId;
            var last = _reservation_IOC._consume_EFCore.QueryAll(d => d.CVid == vid).OrderByDescending(d => d.CCreateTime).Select(d => d.CBalance).FirstOrDefault();
            var customer = _reservation_IOC._customer_EFCore.QueryAll(d => d.CId == cid).SingleOrDefault();

            var vip = _reservation_IOC._vIP_EFCore.QueryAll(d => d.VCid == cid).Single();
            if (last == null || last == 0)
            {
                Consume consume = new Consume()
                {
                    CId = Config.GUID2(),
                    CVid = vid,
                    CCreateTime = DateTime.Now,
                    CBalance = dto.money,
                    CPid = null,
                    CMoney = dto.money,
                    CType = 0,
                };
                _reservation_IOC._consume_EFCore.Add(consume);
            }
            else
            {
                Consume consume = new Consume()
                {
                    CId = Config.GUID2(),
                    CVid = vid,
                    CCreateTime = DateTime.Now,
                    CBalance = last + dto.money,
                    CPid = null,
                    CMoney = dto.money,
                    CType = 0,
                };
                _reservation_IOC._consume_EFCore.Add(consume);
            }


            await _reservation_IOC._consume_EFCore.SaveChangesAsync();

            vip.VRecharge = _reservation_IOC._consume_EFCore.QueryAll(d => d.CType == 0 && d.CVid == vid).Select(d => d.CMoney).ToList().Sum();

            var did = "";
            var recharge = _reservation_IOC._consume_EFCore.QueryAll(d => d.CType == 0 && d.CVid == vid).Select(d => d.CMoney).ToList().Sum();
            var types = _reservation_IOC._dictionary_EFCore.QueryAll(d => d.DDtId == "6e78ff75ecf811ef9301902e1656e0d2").ToList();
            types.Select(d => d.DDesc).ToList().ForEach(d =>
            {
                if (recharge > Convert.ToDouble(d))
                {
                    did = types.Where(e => e.DDesc == d).FirstOrDefault()!.DId;
                }
            });
            vip.VDid = did;
            customer!.CDid = did;
            if (recharge > 0)
            {
                vip.VActive = 1;
                vip.VActiveTime = DateTime.Now;

            }
            _reservation_IOC._customer_EFCore.Update(customer);
            await _reservation_IOC._customer_EFCore.SaveChangesAsync();
            _reservation_IOC._vIP_EFCore.Update(vip);
            await _reservation_IOC._vIP_EFCore.SaveChangesAsync();

            return Result(1, "操作成功");
        }

        public async Task<Api_Response_Dto> GetName(string phone)
        {
            var iqq = _reservation_IOC._customer_EFCore.QueryAll(d => d.CPhone == phone);
            if (!await iqq.AnyAsync())
            {
                return Result(1, "操作成功", "无");
            }
            var iq = _reservation_IOC._customer_EFCore.QueryAll(d => d.CPhone == phone).SingleOrDefault()!;
            var vipid = _reservation_IOC._vIP_EFCore.QueryAll(d => d.VCid == iq.CId).SingleOrDefault()!.VId;
            var balance = _reservation_IOC._consume_EFCore.QueryAll(d => d.CVid == vipid);
            if (!balance.Any())
            {
                return Result(1, "操作成功", data: new
                {
                    name = iq.CName,
                    balance = 0
                });
            }
            return Result(1, "操作成功", data: new
            {
                name = iq.CName,
                balance = balance.OrderByDescending(d => d.CCreateTime).First()!.CBalance,
            });
        }

        public async Task<Api_Response_Dto> addreservation(Reservation_Request_Dto dto)
        {
            var iq = _reservation_IOC._customer_EFCore.QueryAll(d => d.CPhone == dto.phone);
            if (!await iq.AnyAsync())
            {
                return Result(0, "账号不存在");
            }
            if (Convert.ToDateTime(dto.date) < DateTime.Now)
            {
                return Result(0, "时间不能小于当前时间");
            }
            int? time = 0;
            if (dto.allproduct != null || dto.allproduct!.Count != 0)
            {
                dto.allproduct!.ForEach(d =>
                {
                    time = time + d.pDuration;
                });
            }
            if (dto.allsetmenu != null || dto.allsetmenu!.Count != 0)
            {
                dto.allsetmenu!.ForEach(d =>
                {
                    time = time + d.time;
                });
            }
            var rid = Guid.NewGuid().ToString().Replace("-", "");
            SysReservation sysReservation = new SysReservation()
            {
                Rcid = iq.Single().CId,
                Rid = rid,
                Risactive = 0,
                Rprice = dto.sum,
                Rstate = 0,
                Rtime = Convert.ToDateTime(dto.date),
                Ruid = dto.technician,
                RendTime = Convert.ToDateTime(dto.date).AddMinutes(Convert.ToDouble(time))
            };
            _reservation_IOC._sys_Reservation_EFCore.Add(sysReservation);
            if (dto.allsetmenu != null || dto.allsetmenu!.Count != 0)
            {
                dto.allsetmenu!.ForEach(d =>
                {
                    if (d.count != 0)
                    {
                        var pid = _reservation_IOC._product_Package_Details_EFCore.QueryAll(e => e.PpdPpId == d.id).Select(e => e.PpdPId).ToList();
                        pid.ForEach(f =>
                        {
                            SysReservationDetail sysReservationDetail = new SysReservationDetail()
                            {
                                Rdid = Guid.NewGuid().ToString().Replace("-", ""),
                                RdcreateTime = DateTime.Now,
                                Rdpid = f,
                                Rid = rid,
                                Rdprice = dto.sum,
                            };
                            _reservation_IOC._sys_Reservation_Details_EFCore.Add(sysReservationDetail);
                        });
                    }

                });
            }
            if (dto.allproduct != null || dto.allproduct!.Count != 0)
            {
                dto.allproduct!.ForEach(d =>
                {
                    if (d.count != 0)
                    {
                        SysReservationDetail sysReservationDetail = new SysReservationDetail()
                        {
                            Rdid = Guid.NewGuid().ToString().Replace("-", ""),
                            RdcreateTime = DateTime.Now,
                            Rdpid = d.pid,
                            Rid = rid,
                            Rdprice = dto.sum,
                        };
                        _reservation_IOC._sys_Reservation_Details_EFCore.Add(sysReservationDetail);
                    }

                });
            }
            await _reservation_IOC._sys_Reservation_EFCore.SaveChangesAsync();
            await _reservation_IOC._sys_Reservation_Details_EFCore.SaveChangesAsync();
            return Result(1, "操作成功");

        }

        public async Task<Api_Response_Dto> bindallbyids(string pids, string setmenuids)
        {
            List<Product_Response_Dto> list = new List<Product_Response_Dto>();
            pids.Split(',').ToList().ForEach(p =>
            {
                Product_Response_Dto product = new Product_Response_Dto();
                var pro = _reservation_IOC._sys_Product_EFCore.QueryAll(d => d.Pid == p).FirstOrDefault()!;
                product.total_price = pro!.Pprice;
                product.pDuration = pro.PDuration;
                product.pexplain = pro.Pexplain;
                product.count = 1;
                product.pid = pro.Pid;
                product.sum = product.count * product.total_price;
                product.pname = pro.Pname;
                product.img = pro.Pimage;
                list.Add(product);
            });
            double? sum = list.Select(d => d.total_price).Sum();
            List<Package_Response_Dto> list2 = new List<Package_Response_Dto>();
            setmenuids.Split(',').ToList().ForEach(p =>
            {
                Package_Response_Dto product = new Package_Response_Dto();
                var pro = _reservation_IOC._product_Package_EFCore.QueryAll(d => d.PpId == p).FirstOrDefault();
                var pids2 = _reservation_IOC._product_Package_Details_EFCore.QueryAll(d => d.PpdPpId == p).Select(d => d.PpdPId).ToList();
                int? time = 0;
                pids2.ForEach(d =>
                {
                    var time2 = _reservation_IOC._sys_Product_EFCore.QueryAll(e => e.Pid == d).Select(e => e.PDuration).FirstOrDefault();
                    time += time2;
                });
                product.total_price = pro!.PpTotalPrice;
                product.time = time;
                product.explain = pro.PpExplain;
                product.total_price2 = _reservation_IOC._product_Package_Details_EFCore.QueryAll(d => d.PpdPpId == p).FirstOrDefault()!.PpdTotalPrice;
                product.count = 1;
                product.id = pro.PpId;
                product.discountmoney = product.total_price2 - product.total_price;
                product.sumdiscount = product.discountmoney;
                product.sum = product.count * product.total_price;
                product.img = pro.PpImg;
                product.name = pro.PpName;
                list2.Add(product);
            });
            double? sum2 = list2.Select(d => d.total_price).Sum();
            sum = sum + sum2;
            double? discount = list2.Select(d => d.sumdiscount).Sum();
            await _reservation_IOC._sys_Product_EFCore.SaveChangesAsync();
            return Result(1, "操作成功", data: new
            {
                list,
                list2,
                sum,
                discount,
            });
        }

        public async Task<Api_Response_Dto> bindallreservation(string key)
        {
            var iq = await _reservation_IOC._customer_EFCore.QueryAll(d => (d.CName!.Contains(key) || d.CPhone!.Contains(key))).ToListAsync();
            List<Reservation_Response_Dto> list = new List<Reservation_Response_Dto>();
            iq.ForEach(d =>
            {
                var reservation = _reservation_IOC._sys_Reservation_EFCore.QueryAll(e => e.Rcid == d.CId && e.Rstate == 0).SingleOrDefault();

                if (reservation != null)
                {
                    var product = _reservation_IOC._sys_Reservation_Details_EFCore.QueryAll(e => e.Rid == reservation!.Rid).Select(e => e.Rdpid);
                    var img = _reservation_IOC._sys_Product_EFCore.QueryAll(e => e.Pid == product.FirstOrDefault()).Select(e => e.Pimage).SingleOrDefault();
                    List<string> pnames = new List<string>();
                    product.ToList().ForEach(f =>
                    {
                        var name = _reservation_IOC._sys_Product_EFCore.QueryAll(g => g.Pid == f).Select(g => g.Pname).FirstOrDefault();
                        pnames.Add(name!);
                    });

                    Reservation_Response_Dto dto = new Reservation_Response_Dto()
                    {
                        cid = d.CId,
                        cname = d.CName,
                        begindate = reservation.Rtime!.Value.ToString("yyyy-MM-dd:HH-mm"),
                        enddate = reservation.RendTime!.Value.ToString("yyyy-MM-dd:HH-mm"),
                        img = img,
                        pname = pnames,
                        uname = _reservation_IOC._sys_User_EFCore.QueryAll(e => e.Uid == reservation.Ruid).Select(e => e.Uname).FirstOrDefault(),
                        price = reservation.Rprice,
                        rid = reservation.Rid,
                        time = (reservation.RendTime - reservation.Rtime)!.Value.TotalMinutes,
                    };
                    list.Add(dto);
                }
            });
            return Result(1, "操作成功", data: list);
        }

        public async Task<Api_Response_Dto> bindproductbyids(string pids)
        {
            List<Product_Response_Dto> list = new List<Product_Response_Dto>();
            pids.Split(',').ToList().ForEach(p =>
            {
                Product_Response_Dto product = new Product_Response_Dto();
                var pro = _reservation_IOC._sys_Product_EFCore.QueryAll(d => d.Pid == p).FirstOrDefault()!;
                product.total_price = pro!.Pprice;
                product.pDuration = pro.PDuration;
                product.pexplain = pro.Pexplain;
                product.count = 1;
                product.pid = pro.Pid;
                product.sum = product.count * product.total_price;
                product.pname = pro.Pname;
                product.img = pro.Pimage;
                list.Add(product);
            });
            double? sum = list.Select(d => d.total_price).Sum();
            await _reservation_IOC._sys_Product_EFCore.SaveChangesAsync();
            return Result(1, "操作成功", data: new
            {
                list,
                sum,
            });
        }

        public async Task<Api_Response_Dto> bindsetmenubyids(string setmenuids)
        {
            List<Package_Response_Dto> list = new List<Package_Response_Dto>();
            setmenuids.Split(',').ToList().ForEach(p =>
            {
                Package_Response_Dto product = new Package_Response_Dto();
                var pro = _reservation_IOC._product_Package_EFCore.QueryAll(d => d.PpId == p).FirstOrDefault();
                var pids2 = _reservation_IOC._product_Package_Details_EFCore.QueryAll(d => d.PpdPpId == p).Select(d => d.PpdPId).ToList();
                int? time = 0;
                pids2.ForEach(d =>
                {
                    var time2 = _reservation_IOC._sys_Product_EFCore.QueryAll(e => e.Pid == d).Select(e => e.PDuration).FirstOrDefault();
                    time += time2;
                });
                product.total_price = pro!.PpTotalPrice;
                product.time = time;
                product.explain = pro.PpExplain;
                product.total_price2 = _reservation_IOC._product_Package_Details_EFCore.QueryAll(d => d.PpdPpId == p).FirstOrDefault()!.PpdTotalPrice;
                product.count = 1;
                product.id = pro.PpId;
                product.discountmoney = product.total_price2 - product.total_price;
                product.sumdiscount = product.discountmoney;
                product.sum = product.count * product.total_price;
                product.img = pro.PpImg;
                product.name = pro.PpName;
                list.Add(product);
            });
            double? sum = list.Select(d => d.total_price).Sum();
            double? discount = list.Select(d => d.sumdiscount).Sum();
            await _reservation_IOC._sys_Product_EFCore.SaveChangesAsync();
            return Result(1, "操作成功", data: new
            {
                list,
                sum,
                discount,
            });
        }

        public async Task<Api_Response_Dto> GetAllUser(string date)
        {
            var iq = await _reservation_IOC._sys_User_EFCore.QueryAll(d => d.UisBan == 0).Select(d => new User_Response_Dto
            {
                id = d.Uid,
                name = d.Uname!,
            }).ToListAsync();
            iq.ForEach(d =>
            {
                var nb = _reservation_IOC._sys_Reservation_EFCore.QueryAll(e => e.Ruid!.Contains(d.id) && e.RendTime > Convert.ToDateTime(date));
                if (nb.Any())
                {
                    d.disabled = true;
                }
                else
                {
                    d.disabled = false;
                }
            });
            return Result(1, "操作成功", data: iq);
        }

        public async Task<Api_Response_Dto> GetReservationByid(string activeName)
        {
            if (activeName == null)
            {
                return Result(1, "参数错误");
            }
            if (activeName == "setmenu")
            {
                DateTime now = DateTime.Now;
                var iq = await _reservation_IOC._product_Package_EFCore.QueryAll(d => d.PpIsActive == 0 && d.PpBeginTime <= now && d.PpEndTime >= d.PpEndTime).Select(d => new Package_Response_Dto()
                {
                    id = d.PpId,
                    name = d.PpName,
                    desc = d.PpDesc,
                    begintime = d.PpBeginTime!.Value.ToString("yyyy-MM-dd"),
                    endtime = d.PpEndTime!.Value.ToString("yyyy-MM-dd"),
                    createtime = d.PpCreateTime!.Value.ToString("yyyy-MM-dd:HH-MM"),
                    Discount = d.PpDiscount,
                    explain = d.PpExplain,
                    isActive = d.PpIsActive,
                    Stock = d.PpStock,
                    img = d.PpImg,
                    total_price = d.PpTotalPrice,
                    salescount = d.PpSalescount,
                    time = 0
                }).ToListAsync();
                iq.ForEach(d =>
                {
                    d.children = _reservation_IOC._product_Package_Details_EFCore.QueryAll(e => e.PpdPpId == d.id).Select(e => new package_Detail_Response_Dto()
                    {
                        id = e.PpdId,
                        pid = e.PpdPId,
                        ppid = e.PpdPpId,
                        price = e.PpdPrice,
                        quantity = e.PpdQuantity,
                        totalprice = e.PpdTotalPrice,
                    }).ToList();
                    d.total_price2 = _reservation_IOC._product_Package_Details_EFCore.QueryAll(e => e.PpdPpId == d.id).Select(e => e.PpdTotalPrice).FirstOrDefault();
                    int? time = 0;
                    d.children.ForEach(e =>
                    {
                        var time1 = _reservation_IOC._sys_Product_EFCore.QueryAll(f => f.Pid == e.pid).Select(f => f.PDuration).FirstOrDefault();
                        time += time1;
                    });
                    d.time = time;
                });
                return Result(1, "操作成功", iq);
            }
            if (activeName == "physicalobject")
            {
                var alltypee = _reservation_IOC._sys_Product_Type_EFCore.QueryAll(d => d.PtParentId == "02cca692f8a011efae2cd49390200e60").Select(d => d.Ptid).ToList();
                List<Product_Response_Dto> list = new List<Product_Response_Dto>();
                alltypee.ForEach(d =>
                {
                    var product = _reservation_IOC._sys_Product_EFCore.QueryAll(e => e.Ptid == d).Select(e => new Product_Response_Dto
                    {
                        pCount = e.Pno,
                        pid = e.Pid,
                        pcreatetime = e.Pcreatetime!.Value.ToString("yyyy-MM-dd:HH-mm"),
                        pData = e.Pdata!.Value.ToString("yyyy-MM-dd:HH-mm"),
                        pDuration = e.PDuration,
                        pexplain = e.Pexplain,
                        img = e.Pimage,
                        pislist = e.Pislist,
                        PIstop = e.PisTop,
                        pname = e.Pname,
                        pno = e.Pno,
                        pprice = e.Pprice,
                        psales = e.Psales,
                        pshelf = e.Pshelf,
                        ptid = e.Ptid,
                    }).ToList();
                    product.ForEach(f =>
                    {
                        list.Add(f);
                    });
                });
                list.ForEach(d =>
                {
                    d.ptname = _reservation_IOC._sys_Product_Type_EFCore.QueryAll(e => e.Ptid == d.ptid).Select(e => e.Ptname).FirstOrDefault();
                    d.ptype = _reservation_IOC._sys_Product_Type_EFCore.QueryAll(e => e.Ptid == d.ptid).Select(e => e.Ptname).FirstOrDefault();
                });
                return Result(1, "操作成功", data: list);
            }
            if (activeName == "service")
            {
                var alltypee = _reservation_IOC._sys_Product_Type_EFCore.QueryAll(d => d.PtParentId == "044c8e08f8a011efae2cd49390200e60").Select(d => d.Ptid).ToList();
                List<Product_Response_Dto> list = new List<Product_Response_Dto>();
                alltypee.ForEach(d =>
                {
                    var product = _reservation_IOC._sys_Product_EFCore.QueryAll(e => e.Ptid == d).Select(e => new Product_Response_Dto
                    {
                        pCount = e.Pno,
                        pid = e.Pid,
                        pcreatetime = e.Pcreatetime!.Value.ToString("yyyy-MM-dd:HH-mm"),
                        pData = e.Pdata!.Value.ToString("yyyy-MM-dd:HH-mm"),
                        pDuration = e.PDuration,
                        pexplain = e.Pexplain,
                        img = e.Pimage,
                        pislist = e.Pislist,
                        PIstop = e.PisTop,
                        pname = e.Pname,
                        pno = e.Pno,
                        pprice = e.Pprice,
                        psales = e.Psales,
                        pshelf = e.Pshelf,
                        ptid = e.Ptid,
                    }).ToList();
                    product.ForEach(f =>
                    {
                        list.Add(f);
                    });
                });
                list.ForEach(d =>
                {
                    d.ptname = _reservation_IOC._sys_Product_Type_EFCore.QueryAll(e => e.Ptid == d.ptid).Select(e => e.Ptname).FirstOrDefault();
                    d.ptype = _reservation_IOC._sys_Product_Type_EFCore.QueryAll(e => e.Ptid == d.ptid).Select(e => e.Ptname).FirstOrDefault();
                });
                return Result(1, "操作成功", data: list);
            }
            return Result(0, "参数错误");
        }

        public async Task<Api_Response_Dto> updatereservation(Reservation_Request_Dto dto)
        {
            var iq = _reservation_IOC._sys_Reservation_EFCore.QueryAll(d => d.Rid == dto.id);
            if (!await iq.AnyAsync())
            {
                return Result(0, "参数错误");
            }
            var reservation = iq.Single();
            reservation.Rstate = 1;
            _reservation_IOC._sys_Reservation_EFCore.Update(reservation);
            await _reservation_IOC._sys_Reservation_EFCore.SaveChangesAsync();
            return Result(1, "操作成功");
        }
    }
}
